﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Dapper;
using Newtonsoft.Json;

namespace ComTools
{
	public partial class frmSqlServer : Form
	{
		public frmSqlServer()
		{
			InitializeComponent();
		}

		IDbConnection _connection = null;

		private void frmGateway_Load(object sender, EventArgs e)
		{
			ReloadData();
		}

		private void ReloadData()
		{
			txtSqlEditor.Document.HighlightingStrategy =
				ICSharpCode.TextEditor.Document.HighlightingStrategyFactory.CreateHighlightingStrategy("TSQL");
			//
			txtDBSource.Text = "172.16.10.86";
			checkBox1.Checked = false;
			txtUserName.Text = "sa";
			txtPwd.Text = "sa";
			cmbDBName.Text = "Cowain";
			//
			txtDBConnStr.Text = $"Data Source={txtDBSource.Text };Initial Catalog={cmbDBName.Text};User ID={txtUserName.Text};Password={txtPwd.Text}";
			_connection = new System.Data.SqlClient.SqlConnection(txtDBConnStr.Text);
		}

		private void toolStripButton2_Click(object sender, EventArgs e)
		{
			ReloadData();
		}

		private void btnOpenDBSet_Click(object sender, EventArgs e)
		{
			Microsoft.Data.ConnectionUI.DataConnectionDialog dialog = new Microsoft.Data.ConnectionUI.DataConnectionDialog();
			//添加数据源
			//dialog.DataSources.Add(Microsoft.Data.ConnectionUI.DataSource.AccessDataSource);
			//dialog.DataSources.Add(Microsoft.Data.ConnectionUI.DataSource.OdbcDataSource);
			//dialog.DataSources.Add(Microsoft.Data.ConnectionUI.DataSource.OracleDataSource);
			dialog.DataSources.Add(Microsoft.Data.ConnectionUI.DataSource.SqlDataSource);
			//dialog.DataSources.Add(Microsoft.Data.ConnectionUI.DataSource.SqlFileDataSource);
			//设置默认数据提供对象
			dialog.SelectedDataSource = Microsoft.Data.ConnectionUI.DataSource.SqlDataSource;
			dialog.SelectedDataProvider = Microsoft.Data.ConnectionUI.DataProvider.SqlDataProvider;
			dialog.Text = "连接数据库";
			//只能够通过DataConnectionDialog类的静态方琺Show出对话框
			//不同使用dialog.Show()或dialog.ShowDialog()来呈现对话框
			if (Microsoft.Data.ConnectionUI.DataConnectionDialog.Show(dialog) == System.Windows.Forms.DialogResult.OK)
			{
				//连接字符串"Data Source=LENOVO-PC\\MYSQLEXPRESS;Initial Catalog=TestDB;Integrated Security=True"
				txtDBConnStr.Text = dialog.ConnectionString;

				var builder = new System.Data.SqlClient.SqlConnectionStringBuilder(txtDBConnStr.Text);

				txtDBSource.Text = builder.DataSource;
				cmbDBName.Text = builder.InitialCatalog;
				txtUserName.Text = builder.UserID;
				txtPwd.Text = builder.Password;

				checkBox1.Checked = builder.IntegratedSecurity;
				//
				_connection = new System.Data.SqlClient.SqlConnection(txtDBConnStr.Text);
			}
		}

		private void btnRun_Click(object sender, EventArgs e)
		{
			if (_connection != null)
			{
				var sql = txtSqlEditor.Text.Trim();
				if (!string.IsNullOrWhiteSpace(sql))
				{
					DataTable dt = new DataTable(Guid.NewGuid().ToString());
					try
					{
						var reader = _connection.ExecuteReader(sql);
						dt.Load(reader);
						dataGridView1.DataSource = dt;
						//
						tabControl1.SelectedIndex++;
					}
					catch (Exception exc)
					{
						MessageBox.Show(exc.Message);
					}
				}
			}
		}

        private void btnConv2Json_Click(object sender, EventArgs e)
        {
			DataTable dt = dataGridView1.DataSource as DataTable;
			if (dt != null)
			{
				//
				JsonSerializerSettings jsetting = new JsonSerializerSettings();
				jsetting.NullValueHandling = cbxIgnoreNullProperty.Checked ? NullValueHandling.Ignore : NullValueHandling.Include;				
				richTextBox1.Text = JsonConvert.SerializeObject(dt, Formatting.Indented, jsetting);
				tabControl1.SelectedIndex++;
				//var str = Newtonsoft.Json.JsonConvert.SerializeObject(dt);
				//格式化json字符串
				//JsonSerializer serializer = new JsonSerializer();
				//TextReader tr = new StringReader(str);
				//JsonTextReader jtr = new JsonTextReader(tr);
				//object obj = serializer.Deserialize(jtr);
				//if (obj != null)
				//{
				//	StringWriter textWriter = new StringWriter();
				//	JsonTextWriter jsonWriter = new JsonTextWriter(textWriter)
				//	{
				//		Formatting = Formatting.Indented,
				//		Indentation = 4,
				//		IndentChar = ' ',						
				//	};
				//	serializer.Serialize(jsonWriter, obj);
				//richTextBox1.Text = textWriter.ToString();
				//}
				//else
				//{
				//	richTextBox1.Text = str;
				//}
			}
        }
    }
}